<script setup lang="ts" name="RedGreen">
import API from "@/api";
import { userinfo } from "@/store";
import { cloneDeep } from "lodash";
import router from "@/router";

const { t } = useI18n();
const piniaUserinfo: any = userinfo();
const global: any = getCurrentInstance()?.appContext.config.globalProperties;
const route = useRoute();
const images = reactive({
  inputMoney: new URL(
    "@/assets/images/ColorfulLottery/inputMoney.png",
    import.meta.url
  ).href,
  inputMoneyActive: new URL(
    "@/assets/images/ColorfulLottery/inputMoneyActive.png",
    import.meta.url
  ).href,
});

const greenColor = "linear-gradient(309.81deg, #2DBC9C 15.58%, #4AD9B8 84.9%)";
const purpleColor = "linear-gradient(97.14deg, #EA6AFF 1.52%, #A93FFC 97.98%)";
const redColor = "linear-gradient(97.48deg, #FC6B6C 1.58%, #FB2973 110.2%)";
const redPurpleColor =
  "linear-gradient(135deg,#FC4C70 0%,#FC4C70 50%, #C250FE 50%, #C250FE 100%)";
const greenPurpleColor =
  "linear-gradient(135deg,#38C6A6 0%,#38C6A6 50%, #C250FE 50%, #C250FE 100%)";

const typeDigits = [
  {
    bg: redColor,
    name: computed(() => t("bet.bet1")),
    money: "",
    id: 1,
  },
  {
    bg: greenColor,
    name: computed(() => t("bet.bet2")),
    money: "",
    id: 2,
  },
  {
    bg: purpleColor,
    name: computed(() => t("bet.bet3")),
    money: "",
    id: 3,
  },
];

const numberDigits = [
  {
    bg: redPurpleColor,
    name: 0,
    money: "",
    id: 0,
  },
  {
    bg: greenColor,
    name: 1,
    money: "",
    id: 1,
  },
  {
    bg: redColor,
    name: 2,
    money: "",
    id: 2,
  },
  {
    bg: greenColor,
    name: 3,
    money: "",
    id: 3,
  },
  {
    bg: redColor,
    name: 4,
    money: "",
    id: 4,
  },
  {
    bg: greenPurpleColor,
    name: 5,
    money: "",
    id: 5,
  },
  {
    bg: redColor,
    name: 6,
    money: "",
    id: 6,
  },
  {
    bg: greenColor,
    name: 7,
    money: "",
    id: 7,
  },
  {
    bg: redColor,
    name: 8,
    money: "",
    id: 8,
  },
  {
    bg: greenColor,
    name: 9,
    money: "",
    id: 9,
  },
];

const entertainmentDes = computed(() => {
  return {
    title1: t("rule.title52"),
    title1Content: t("rule.test12"),
    title2Content: t("rule.test13"),
    title3Content: t("rule.test14"),
    title2: t("rule.title53"),
    title4Content: t("rule.test15"),
  };
});

const data: any = reactive({
  isShowPayFinished: false,
  tabList: [
    {
      text: computed(() => "预测"),
    },
  ],
  tabIndex: 0,
  moneyList: ["50", "100", "1k", "5k", "10k"],
  moneyIndex: 0,
  isShowInput: false,
  money: "",
  hundredsMoney: 0,
  entertainmentList: [
    {
      titleName: computed(() => "颜色"),
      id: 1,
      numberData: cloneDeep(typeDigits),
    },
    {
      titleName: computed(() => "号码"),
      id: 2,
      numberData: cloneDeep(numberDigits),
    },
  ],
  showBet: false,
  showInstruction: false,
  nowMoney: "50",
  tempResultList: [],
  paramsResult: [],
  totalMoney: "",
  timer: null,
  routeParams: "",
  configList: [],
});
const {
  tabList,
  tabIndex,
  moneyList,
  moneyIndex,
  isShowInput,
  nowMoney,
  routeParams,
  money,
  entertainmentList,
  numerTypeList,
  showBet,
  isShowPayFinished,
  dragonTigerList,
  outOrInList,
  showInstruction,
  tempResultList,
  paramsResult,
  totalMoney,
} = toRefs(data);
let timer: any;

const headerTitle: any = computed(() => {
  return route?.query?.title || "红绿灯";
});

const startCountdown = () => {
  timer = setInterval(() => {
    if (routeParams.value.timeInfo > 0) {
      routeParams.value.timeInfo--;
    } else {
      clearInterval(timer);
      // 倒计时结束后的操作
    }
  }, 1000); // 每秒执行一次
};
const displayTime = computed(() => {
  const hours = Math.floor(routeParams.value.timeInfo / 3600);
  const minutes = Math.floor((routeParams.value.timeInfo % 3600) / 60);
  const seconds = Math.floor(routeParams.value.timeInfo % 60);
  return {
    hours: String(hours).padStart(2, "0"),
    min: String(minutes).padStart(2, "0"),
    seconds: String(seconds).padStart(2, "0"),
  };
});
onMounted(() => {});
onBeforeUnmount(() => {
  clearInterval(timer); // 组件销毁前清除计时器
});

const setConfigData = (list: any[]) => {
  const data = list.map((item) => {
    const str = item?.type?.split("_");
    let thirdNum = str[2];
    return {
      ...item,
      number: +thirdNum,
    };
  });

  entertainmentList.value.forEach((el: any) => {
    el.numberData.forEach((it: any) => {
      let dataFilter = data.filter((fi: any) => fi.code === el.id);
      let item = dataFilter.find((dataIt: any) => dataIt.number === it?.id);

      it.code = item.code;
      it.type = item.type;
      it.number = +item.number;
      (it.odd = item.oddsRatio.toFixed(3)),
        (it.singleMaxMoney = item.singleMaxMoney),
        (it.singleMinMoney = item.singleMinMoney);
    });
  });
};

const handleMoney = (item: any, index: number) => {
  moneyIndex.value = index;
  isShowInput.value = false;
  nowMoney.value = item;
};
const setCurrentMoney = (e: any) => {
  nowMoney.value = e.target.value;
};
const handleInput = () => {
  isShowInput.value = true;
  moneyIndex.value = -1;
};
const cancelPop = () => {
  showBet.value = false;
};
const getDefaultValue = () => {
  return nowMoney.value;
};
const nowDes: any = computed(() => {
  switch (tabIndex.value) {
    case 0:
      return entertainmentDes.value;
  }
});
const setDefaultMoney = (it: any) => {
  switch (nowMoney.value) {
    case "50":
      it.money = 50;
      break;
    case "100":
      it.money = 100;
      break;
    case "500":
      it.money = 500;
      break;
    case "1k":
      it.money = 1000;
      break;
    case "5k":
      it.money = 5000;
      break;
    case "10k":
      it.money = 10000;
      break;
    default:
      it.money = nowMoney.value;
  }
};
const betInterval = (e: any, data: any) => {
  let money = e.target.value;
  if (money > data.singleMaxMoney) {
    data.money = data.singleMaxMoney;
  } else if (money < data.singleMinMoney) {
    if (data.singleMinMoney == 0) {
      data.money = "";
    } else {
      data.money = data.singleMinMoney;
    }
  } else {
    data.money = money;
  }
};
const handleBet = () => {
  if (routeParams.value.timeInfo <= routeParams.value.timeRange) {
    global.message(t("bet.warning1"), { type: "danger" });
    return false;
  }
  paramsResult.value = []; //组装数据结果
  tempResultList.value = []; //投注确认详情
  let newArray: any = [];
  switch (tabIndex.value) {
    case 0:
      newArray = entertainmentList.value;
      break;
    default:
      newArray = [];
  }
  totalMoney.value = 0;
  console.log('newArray', newArray);
  let hasMoenyList: any[] = [];
  newArray.forEach((item: any, groupIndex: number) => {
    hasMoenyList = [...hasMoenyList, ...item.numberData.filter((el: any) => el.money)];
  });
  console.log(hasMoenyList, "hasMoenyList");
  if (hasMoenyList.length > 0) {
    hasMoenyList.forEach((it: any, index: number) => {
      // let firstData = tabIndex.value + 1;
      // let secondData = item.id;
      // let thirdData = it.id;
      // let dataInfo = `${firstData}-${secondData}-${thirdData}`;
      let dataMoney = it.money;
      // paramsResult.value.push(`${dataInfo}:${dataMoney}`);
      let resName = entertainmentList.value.find((eItem: any) => eItem?.id === it?.code)?.titleName;
      let oddNum = it.odd;
      tempResultList.value.push({
        name: resName,
        money: dataMoney,
        odds: oddNum || 0,
        type: it.type,
        bg: it.bg,
        number: it.code === 2 ? it.number : '',
      });
      totalMoney.value = tempResultList.value.reduce(
        (accumulator: any, currentValuea: any) => {
          return +accumulator + +currentValuea.money;
        },
        0
      );
    });
  }

  // console.log(paramsResult.value, "paramsResult.value");
  // console.log(tempResultList.value, "tempResultList--------");
  if (tempResultList.value.length <= 0) {
    global.message(t("bet.warning2"), { type: "danger" });
    return;
  }
  showBet.value = true;
};
const resetMoney = () => {
  entertainmentList.value.forEach((item: any) => {
    clearInput(item.numberData);
  });
};
const clearInput = (list: any) => {
  list.forEach((it: any) => {
    it.money = "";
  });
};
const submitBet = async () => {
  let betContent = tempResultList.value.map((item: any) => {
    return {
      money: item.money,
      content: item.type,
      name: item.name,
    };
  });
  let params = {
    privateId: route?.query?.id,
    allMoney: totalMoney.value,
    betContent: betContent,
    code: tabIndex.value + 1,
    period: routeParams.value.period,
    bigCode: route?.query?.bigCode,
    typeConfigCode: route?.query?.typeConfigCode,
  };
  console.log('submitBet', params)
  try {
    let res = await API.privateOrderBetApi(params);
    if (res?.code === 200) {
      piniaUserinfo.queryUserMoney();
      refreshPage();
      isShowPayFinished.value = true;
    }
  } catch (error) {}
};
// 查看历史
const handleGoHistory = () => {
  router.push(`/me/account?type=${route?.query?.typeConfigCode}`);
};
const refreshPage = async () => {
  try {
    let res = await API.lotteryPrivateAPI({
      planId: route?.query?.planId,
      typeConfigCode: route?.query?.typeConfigCode,
    });
    if (res?.code === 200) {
      let data = res.data.periods[0];
      let timeInfo = Math.floor((data?.endTime - res.data.time) / 1000) + 1;
      let timeRange = Math.floor((data?.endTime - data?.stopBetTime) / 1000);
      routeParams.value = {
        ...data,
        timeInfo,
        timeRange,
      };
      clearInterval(timer);
      startCountdown();
      setConfigData(res.data.typeList);
    }
  } catch (error) {}
};
const closeDialog = () => {
  showBet.value = false;
};
watch(
  [() => route?.query?.planId, () => route?.query?.typeConfigCode],
  ([val1, val2]) => {
    if (val1 && val2) {
      refreshPage();
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => routeParams.value.timeInfo,
  (val) => {
    if (val == 0) {
      refreshPage();
    }
  },
  {
    immediate: true,
  }
);
</script>

<template>
  <DetailHeader :title="headerTitle" :isNeedBackIcon="true" />
  <div class="redGreenPage">
    <van-tabs
      class="headerTabs"
      v-model:active="tabIndex"
      swipe-threshold="1"
      shrink
    >
      <van-tab v-for="(el, index) in tabList" :title="el?.text"> </van-tab>
    </van-tabs>
    <div class="moneyNum">
      <div
        class="moneyItem"
        v-for="(el, index) in moneyList"
        :key="index"
        :class="{ moneyActive: moneyIndex === index }"
        @click="handleMoney(el, index)"
      >
        {{ el }}
      </div>
      <div class="inputMoney">
        <img
          v-if="!isShowInput"
          :src="images.inputMoney"
          alt=""
          @click="handleInput"
        />
        <img v-else :src="images.inputMoneyActive" alt="" />
        <input
          v-model="money"
          @input="setCurrentMoney"
          v-if="isShowInput"
          type="number"
          :placeholder="t('bet.test57')"
        />
      </div>
    </div>
    <div class="bottomInfo">
      <div class="countdown">
        <div class="topTime">
          <div class="leftNum">
            {{ t("bet.test38") }}{{ routeParams.period }}{{ t("bet.test39") }}
          </div>
          <div class="dateTime">{{ t("bet.test40") }}</div>
          <div class="timeData">
            <div class="timeInfo">{{ displayTime.hours }}</div>
            :
            <div class="timeInfo">{{ displayTime.min }}</div>
            :
            <div class="timeInfo">{{ displayTime.seconds }}</div>
          </div>
        </div>
        <div class="line"></div>
        <div class="topTime">
          <div class="leftNum" v-if="routeParams.lastPeriod != null">
            {{ t("bet.test38") }}{{ routeParams.lastPeriod || ""
            }}{{ t("bet.test39") }}
          </div>
          <div class="dateTime">{{ t("bet.test41") }}</div>
          <div class="resultData">
            <div
              class="numItem"
              v-if="routeParams.winningNumber != null"
              v-for="item in routeParams.winningNumber"
              :style="{
                background: numberDigits[+item].bg
              }"
            >
              {{ item }}
            </div>
          </div>
        </div>
      </div>
      <div class="playContainer">
        <div
          class="playTypeItem"
          v-if="tabIndex === 0"
          v-for="(item, parentIndex) in entertainmentList"
          :key="parentIndex"
        >
          <div class="topTitle">{{ item.titleName }}</div>
          <div v-if="item?.id === 1" class="typeData">
            <div class="firstRow">
              <div class="name">{{ item?.code === 1 ? "颜色" : "号码" }}</div>
              <div class="type">
                <div
                  class="num1"
                  :style="{ background: num.bg }"
                  v-for="(num, index) in item.numberData"
                  :key="index"
                ></div>
              </div>
            </div>
            <div class="secondRow">
              <div class="name">{{ t("bet.test43") }}</div>
              <div class="Odds">
                <div v-for="(el, index) in item.numberData" :key="el.id">
                  {{ el.odd }}
                </div>
              </div>
            </div>
            <div class="thirdRow">
              <div class="name">{{ t("bet.test44") }}</div>
              <div class="moneyInfo">
                <div
                  class="inputMoney"
                  :class="{ showMinWidth: it.showMinWidth }"
                  v-for="(it, index) in item.numberData"
                  :key="it.id"
                >
                  <input
                    type="number"
                    v-model="it.money"
                    @focus="setDefaultMoney(it)"
                    @blur="(e) => betInterval(e, it)"
                  />
                </div>
              </div>
            </div>
          </div>
          <div v-if="item?.id === 2" class="content">
            <div class="left-bar">
              <div>{{ t("bet.test42") }}</div>
              <div>{{ t("bet.test43") }}</div>
              <div>{{ t("bet.test44") }}</div>
              <div>{{ t("bet.test42") }}</div>
              <div>{{ t("bet.test43") }}</div>
              <div>{{ t("bet.test44") }}</div>
            </div>
            <div class="list">
              <div class="bottomData" v-for="it in item.numberData">
                <div class="number" :style="{ background: it.bg }">
                  {{ it.name }}
                </div>
                <div class="rate">{{ it.odd }}</div>
                <input
                  class="input"
                  v-model="it.money"
                  @focus="setDefaultMoney(it)"
                  @blur="(e) => betInterval(e, it)"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="betAction">
      <div @click="showInstruction = true" class="winningRemark">
        <Iconfont
          name="icon-icon_shuoming"
          color="#FF6F1E"
          size="20"
          class="remarkIcon"
        /><span>{{ t("bet.test45") }}</span>
      </div>
      <van-button round class="reset" type="primary" @click="resetMoney">{{
        t("bet.btn4")
      }}</van-button>
      <van-button @click="handleBet" round class="bet" type="primary">{{
        t("bet.btn5")
      }}</van-button>
    </div>
    <van-popup
      v-model:show="showBet"
      round
      position="bottom"
      class="confirmBetPop"
    >
      <div class="popTitle">
        <div>{{ t("bet.test46") }}</div>
        <Iconfont
          @click="cancelPop"
          class="closeIcon"
          name="icon-icon_close"
          color="#FF2D55"
          size="20"
        />
      </div>
      <div class="centerContent">
        <div class="betDetail">
          <div class="detailRow">
            <div>
              {{ t("bet.test47") }}<span>{{ routeParams.planName }}</span>
            </div>
            <div>{{ t("bet.test48") }}</div>
            <div
              class="rowData"
              v-for="(item, index) in tempResultList"
              :key="index"
            >
              <span>{{ item.name }} </span>
              <span class="radius" :style="{
                background: item?.bg
              }">{{ item.number }}</span>
              <span class="money">₹{{ item.money }}</span>
            </div>
            <div>
              {{ t("bet.test49") }}：<span
                ><span class="period">{{ routeParams.period }}</span>
                {{ t("bet.test39") }}</span
              >
            </div>
            <div>
              {{ t("bet.test55") }}：<span class="totalMoney"
                >₹{{ Number(totalMoney).toFixed(2) }}</span
              >
            </div>
          </div>
        </div>
        <div class="operateBtn">
          <van-button
            class="cancel"
            round
            type="primary"
            @click="showBet = false"
            >{{ t("bet.btn6") }}</van-button
          >
          <van-button
            class="confirm"
            round
            @click="submitBet"
            type="primary"
            :disabled="!tempResultList.length"
            >{{ t("bet.btn7") }}</van-button
          >
        </div>
      </div>
    </van-popup>
    <van-popup
      v-model:show="showInstruction"
      round
      position="bottom"
      class="confirmBetPop"
    >
      <div class="popTitle">
        <div>{{ t("bet.test45") }}</div>
        <Iconfont
          @click="showInstruction = false"
          class="closeIcon"
          name="icon-icon_close"
          color="#FF2D55"
          size="20"
        />
      </div>
      <div class="remarkContent">
        <div class="titleName">{{ nowDes?.title1 }}</div>
        <div class="contentDetail">{{ nowDes?.title1Content }}</div>
        <div class="contentDetail">{{ nowDes?.title2Content }}</div>
        <div class="contentDetail">{{ nowDes?.title3Content }}</div>
        <div class="titleName">{{ nowDes?.title2 }}</div>
        <div class="contentDetail">{{ nowDes?.title4Content }}</div>
      </div>
    </van-popup>
    <van-dialog
      class="payDialog"
      v-model:show="isShowPayFinished"
      :title="t('bet.test56')"
      show-cancel-button
      @cancel="closeDialog"
      :cancel-button-text="t('bet.btn2')"
      cancel-button-color="#9CA2A9"
      :confirm-button-text="t('bet.btn3')"
      confirm-button-color="#3497FB"
      @confirm="handleGoHistory"
    >
      <img src="@/assets/images/Bet/success.svg" alt="" />
    </van-dialog>
  </div>
</template>

<style lang="scss" scoped>
@import url("./index.scss");
</style>
<style lang="scss">
.payDialog {
  text-align: center;
  .van-dialog__header {
    color: #ff2d55;
  }
  .van-dialog__content {
    img {
      margin: 15rem auto;
      width: 50rem;
      height: 50rem;
    }
  }
}
</style>
